package com.feng.fengDUtil;

import com.alibaba.fastjson.JSONObject;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.springframework.util.CollectionUtils;

public class TransUtil {

  public static <K, T> Map<K, T> transToMap(Collection<T> collections,
      Function<T, K> keyFunc) {
    return transToMap(collections, null, keyFunc, Function.identity());
  }

  public static <K, V, T> Map<K, V> transToMap(Collection<T> collections,
      Function<T, K> keyFunc, Function<T, V> valueFunc) {
    return transToMap(collections, null, keyFunc, valueFunc);
  }

  public static <K, V, T> Map<K, V> transToMap(Collection<T> collections,
      Predicate<T> predicate,
      Function<T, K> keyFunc, Function<T, V> valueFunc) {
    Stream<T> stream = collections.stream();
    if (predicate != null) {
      stream = stream.filter(predicate);
    }
    return stream.collect(Collectors.toMap(keyFunc, valueFunc, (k, v) -> k));
  }

  public static <T, K> Map<K, List<T>> transToStrList(Collection<T> collection, Function<T, K> keyFunc) {
    return transToStrList(collection, null, null, keyFunc, Function.identity());
  }

  public static <T, K, V> Map<K, List<V>> transToStrList(Collection<T> collection,
      Function<T, K> keyFunc, Function<T, V> valFunc) {
    return transToStrList(collection, null, null, keyFunc, valFunc);
  }

  public static <T, K, V> Map<K, List<V>> transToStrList(Collection<T> collection,
      Predicate<T> predicate,
      Comparator<T> comparator, Function<T, K> keyFunc, Function<T, V> valFunc) {
    if (CollectionUtils.isEmpty(collection)) {
      return new HashMap<>();
    }
    Stream<T> stream = collection.stream().filter(n -> keyFunc.apply(n) != null);
    if (predicate != null) {
      stream = stream.filter(predicate);
    }
    if (comparator != null) {
      stream = stream.sorted(comparator);
    }
    return stream
        .collect(Collectors.groupingBy(keyFunc, Collectors.mapping(valFunc, Collectors.toList())));
  }


  public static List<String> getNumber(String s) {
    System.out.println(s);
    return new ArrayList<>();
  }

  public static void main(String[] args) {
    Map<String, List<String>> map = new HashMap<>();
    //map.put("a", new ArrayList<>());
    map.computeIfAbsent("a", TransUtil::getNumber).add("99");
    System.out.println(JSONObject.toJSONString(map));
  }

  public static <T, R> List<R> mapToList(List<T> data, Function<T, R> function) {
    return data.stream().map(function).collect(Collectors.toList());
  }
}
